package com.lais.record.base.interceptor;

import com.lais.record.base.properties.JwtProperties;
import com.lais.record.common.auth.UserInfo;
import com.lais.record.common.constant.RecordEnum;
import com.lais.record.common.exception.RecordException;
import com.lais.record.common.utils.JwtUtils;
import com.lais.record.common.utils.UserInfoThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: luowen
 * @Description: 登录拦截器
 * @Date: Create in 22:54 2019/11/28
 */
@Slf4j
@Component
public class LoginInteceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public  boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authRecord = request.getHeader("auth_record");
        if(StringUtils.isEmpty(authRecord)){
            log.error("登录拦截器---请求头中不存在登录信息");
            throw new RecordException(RecordEnum.USER_NO_LOGIN.getCode(),RecordEnum.USER_NO_LOGIN.getMessage());
        }
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(authRecord, jwtProperties.getPublicKey());
            UserInfoThreadLocal.set(userInfo);

        }catch (Exception e){
            log.error("登录拦截器---token异常");
            throw new RecordException(RecordEnum.USER_NO_LOGIN.getCode(),RecordEnum.USER_NO_LOGIN.getMessage());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserInfoThreadLocal.remove();
    }
}
